from datetime import datetime
from src.common.config import config
from src.common.logger import getLogger
from src.agentic.agent.AgentTools import AgentTools
from src.modules.rag.service import document_service
from src.agentic.config.VectorStore import VectorStore
from src.agentic.config.LanguageModel import LanguageModel
from src.agentic.rag.advance.AdaptiveRAG import AdaptiveRAG
from src.agentic.config.EmbeddingModel import EmbeddingModel
from src.agentic.rag.advance.SelfCheckRAG import SelfCheckRAG
from src.agentic.rag.advance.CorrectiveRAG import CorrectiveRAG
from src.modules.memory.service import HistoryRecordService, MemoryDetailService

logger = getLogger()

def invoke_retrieval_advance(form):
    start_time = datetime.now().second

    HistoryRecordService.insert_history_memory(form)

    base_url = "http://localhost:11434"
    llm_model = LanguageModel("qwen3:4b", base_url, None)
    llm = llm_model.new_llm_model()

    embed_model = EmbeddingModel("bge-m3", base_url)
    embedding = embed_model.new_embed_model()

    config_dict = config.parse_config_key(["qdrant"])
    collection_prefix = config_dict.get("collection_prefix", "")
    logger.info(f"invoke_retrieval_advance collection_prefix: {collection_prefix}")

    vector_store = None
    library_number = form.get("library")
    logger.info(f"invoke_retrieval_advance library_number: {library_number}")
    if library_number:
        vector_store = VectorStore().new_vector_store(embedding, collection_prefix + library_number)

    agent_tools = AgentTools()
    tools = agent_tools.get_execute_tools()

    rag_retriever = None
    ragPattern = form.get("pattern")
    logger.info(f"invoke_retrieval_advance ragPattern: {ragPattern}")
    if ragPattern == "Corrective":
        rag_retriever = CorrectiveRAG(llm, vector_store, tools)
    elif ragPattern == "SelfCheck":
        rag_retriever = SelfCheckRAG(llm, vector_store, tools)
    elif ragPattern == "Adaptive":
        document = document_service.select_document_library(library_number)
        rag_retriever = AdaptiveRAG(llm, vector_store, tools, document.document_summary)
    retrieve_result = rag_retriever.invoke(form.get("query"))

    MemoryDetailService.insert_memory_detail_ai(form, retrieve_result)

    logger.info(f"invoke_retrieval_advance time: {datetime.now().second - start_time} s")
    return retrieve_result
